package com.cby.library.tool.util

import android.text.TextUtils
import android.util.Log
import com.cby.library.tool.log.CbyLogManager

/**
 * @description: CbyLogUtils
 *
 * @author ChenBaoYang
 * @date 6/1/21 10:26
 */
object CbyLogUtils {

    var isDebug = true

    const val PREFIX_TAG = "CbyLogUtils-"
    const val DEFAULT_TAG = "Cby"
    private const val LOG_MSG_PREFIX = "log start --> "
    private const val LOG_MSG_SUFFIX = "<-- log end "
    private const val LOG_SEPARATOR = " - "

    private const val LOG_MAX_LENGTH = 2000

    @JvmStatic
    fun i(tag: String, msg: String?) {
        if (isDebug && !TextUtils.isEmpty(msg)) {
            val strLength: Int = msg?.length ?: 0
            if(strLength > LOG_MAX_LENGTH) {
                CbyLogManager.instance.write2LogFile(msg!!)
            }else{
                Log.i(PREFIX_TAG + tag, msg!!)
            }
        }
    }

    @JvmStatic
    fun d(tag: String, msg: String?) {
        if (isDebug && !TextUtils.isEmpty(msg)) {
            val strLength: Int = msg?.length ?: 0
            if(strLength > LOG_MAX_LENGTH) {
                CbyLogManager.instance.write2LogFile(msg!!)
            }else{
                Log.d(PREFIX_TAG + tag, msg!!)
            }
        }
    }

    @JvmStatic
    fun e(tag: String, msg: String?) {
        if (isDebug && !TextUtils.isEmpty(msg)) {
            val strLength: Int = msg?.length ?: 0
            if(strLength > LOG_MAX_LENGTH) {
                CbyLogManager.instance.write2LogFile(msg!!)
            }else{
                Log.e(PREFIX_TAG + tag, msg!!)
            }
        }
    }

    /**
     * 强制性的日志输出，用于在游戏接入，查看排查
     */
    @JvmStatic
    fun flog(vararg messages: String?) {
        val msgBuilder = StringBuilder(LOG_MSG_PREFIX)
        for (i in messages.indices) {
            msgBuilder.append(messages[i])
            if (i == messages.size - 1) {
                break
            }
            msgBuilder.append(LOG_SEPARATOR)
        }
        msgBuilder.append(LOG_MSG_SUFFIX)
        //处理log
        val stackTrace = Thread.currentThread().stackTrace
        var tag: String = DEFAULT_TAG
        if (stackTrace.size > 4) {
            val log = stackTrace[3]
            tag = log.fileName
            if (tag.contains(".java")) {
                tag = tag.replace(".java", "")
            } else if (tag.contains(".kt")) {
                tag = tag.replace(".kt", "")
            }
        }
        i(tag, msgBuilder.toString())
    }

}